package AdminService

import (
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/gogf/gf/v2/util/grand"
	"seawolf-admin-go/internal/request/BaseReq"
	"seawolf-admin-go/utility/db"
	"seawolf-admin-go/utility/response"
	"seawolf-admin-go/utility/tools"
	"strings"
	"time"
)

func PersonUpdate(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	avatar := r.Get("avatar", "").String()
	password := r.Get("password", "").String()
	ctx := r.GetCtx()
	PhotoPreFixTmp, _ := g.Cfg().Get(ctx, "upload.PhotoPreFix", "")
	avatar = strings.ReplaceAll(avatar, PhotoPreFixTmp.String(), "")
	updateData := g.Map{
		"avatar":    avatar,
		"nickname":  r.Get("nickname", "").String(),
		"realname":  r.Get("realname", "").String(),
		"remark":    r.Get("remark", "").String(),
		"update_at": time.Now().Unix(),
	}

	if password != "" {
		passwordSalt := grand.Letters(10)
		updateData["password_salt"] = passwordSalt
		updateData["password"] = tools.EncryptPassword(password, passwordSalt)
	}

	res, err := db.GetUnSafaTable(ctx, req.TableName).Where(
		"id",
		req.AdminId,
	).Update(updateData)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	row, err := res.RowsAffected()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	if row < 1 {
		return response.FailByRequestMessage(nil, "编辑失败")
	}
	// 清除缓存
	tools.ClaerCacheByKey(ctx, fmt.Sprintf(adminModelCacheTempetle, gconv.String(req.AdminId)))
	return response.SuccessByRequestMessage(nil, "编辑成功")
}
